#!/bin/bash -e

function info() {
echo Usage: `basename $0` '[-d depth_filter] vcf'
exit 1
}

while getopts  ":p:f:i:d:" opt; do
	case  $opt  in
		p) out_prefix=$OPTARG;;
		f) suffix=$OPTARG;;
        i) bed=$OPTARG;;
        d) depth_filter=$OPTARG;;
		*) info;;
	esac
done
shift $(($OPTIND - 1))


if [ $# -lt 1 ]; then info; fi

. $var

vcf=$1
num_thread=8

depth_filter=${depth_filter:=5}

bed1=$data/../data/adm/1_22.bed

# filter site
# filter within bed 
filter_vcf_bed.sh -p$out_prefix.bed $vcf $bed1

# extra depth info
extra_info.sh -p$out_prefix $vcf

# depth filter
depth_filter_adm.py -f$depth_filter -p$out_prefix $out_prefix.fields.txt

sed -i '1s/^#//' $out_prefix.filt.sample.list

# filter for available samples
grep True $out_prefix.filt.sample.list |cut -f1 > $out_prefix.true.sample.list

echo; echo SelectVariants
java $j_mem -jar $gatk \
    -R $ref_genome \
    -T SelectVariants \
    -V $out_prefix.bed.filter.vcf \
    -sf $out_prefix.true.sample.list \
    -o $out_prefix.use.vcf
    
# echo; echo to bed
# java $j_mem -jar $gatk \
    # -R $ref_genome \
    # -T VariantsToBinaryPed \
    # -V variants.vcf \
    # -m metadata.fam \
    # -bed output.bed \
    # -bim output.bim \
    # -fam output.fam

echo generate .ped file
vcftools  --vcf  $out_prefix.use.vcf --plink --out $out_prefix

echo generate .bed
plink --file $out_prefix --make-bed --out $out_prefix

#------------------------------------------------

# filter conjucate? site


plink --file $out_prefix --indep-pairwise 1000 50 0.05
plink --file $out_prefix --extract plink.prune.in --out $out_prefix.filt_chain --make-bed --recode


:<<test
#------------------------------------------------

out_prefix=$out_prefix.filt_chain
cut -f1 $out_prefix.ped -d' ' > $out_prefix.sample.list

echo admixture
for k in `seq 3 9`; do
    admixture --cv -j$num_thread $out_prefix.bed $k > $out_prefix.$k.log
    sed -i 's/ /\t/g' $out_prefix.$k.Q
    paste $out_prefix.sample.list $out_prefix.$k.Q > $out_prefix.$k.q
    
    # str_sort=
    # for j in `seq 2 $k`; do
        # str_sort="$str_sort -k$j,${j}n" 
    # done
    # sort $str_sort $out_prefix.$k.q > $out_prefix.$k.q.sort
    
    # q_bar.py -p$out_prefix.$k $out_prefix.$k.q.sort
    q_bar.py -p$out_prefix.$k $out_prefix.$k.q $out_prefix.sample.list
    q_bar1.py -p$out_prefix.$k $out_prefix.$k.q $out_prefix.sample.list
done

# admixture --cv -s time
test

. $cmd_done
